//给定一个候选人编号的集合 candidates 和一个目标数 target ，找出 candidates 中所有可以使数字和为 target 的组合。 
//
// candidates 中的每个数字在每个组合中只能使用 一次 。 
//
// 注意：解集不能包含重复的组合。 
//
// 
//
// 示例 1: 
//
// 
//输入: candidates = [10,1,2,7,6,1,5], target = 8,
//输出:
//[
//[1,1,6],
//[1,2,5],
//[1,7],
//[2,6]
//] 
//
// 示例 2: 
//
// 
//输入: candidates = [2,5,2,1,2], target = 5,
//输出:
//[
//[1,2,2],
//[5]
//] 
//
// 
//
// 提示: 
//
// 
// 1 <= candidates.length <= 100 
// 1 <= candidates[i] <= 50 
// 1 <= target <= 30 
// 
// Related Topics 数组 回溯 
// 👍 983 👎 0


package com.cjl.leetcode.editor.cn;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * [P40]_组合总和 II
 * @author cjl
 * @date 2022-06-05 17:10:46
 */
public class P40_CombinationSumIi{
      public static void main(String[] args) {
            //测试代码
           Solution solution = new P40_CombinationSumIi().new Solution();
          List<List<Integer>> resList = solution.combinationSum2(new int[]{2,5,2,1,2}, 5);
          for (List<Integer> list : resList) {
              System.out.println("args = " + list);
          }
      }
      //力扣代码
      //leetcode submit region begin(Prohibit modification and deletion)
class Solution {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> resList = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        Arrays.sort(candidates);
        combination(candidates, target, resList, 0, path);
        return resList;
    }

    private void combination(int[] candidates, int target, List<List<Integer>> resList, int curr, List<Integer> path){
        if(target < 0){
            return;
        }
        if(target == 0 ){
            if(!resList.contains(path)){
                resList.add(path);
            }
            return;
        }
        if(curr < candidates.length && target - candidates[curr] >= 0){
            List<Integer> pathcp2 = new ArrayList<>();
            pathcp2.addAll(path);
            pathcp2.add(candidates[curr]);
            combination(candidates, target - candidates[curr], resList, curr+1, pathcp2);
            /**
             * 防止重复计算
             */
            while ( curr < candidates.length-2 && candidates[curr] == candidates[curr +1] ){
                curr = curr+1;
            }
            if(curr < candidates.length-1 && candidates[curr] != candidates[curr +1]){
                List<Integer> pathcp1 = new ArrayList<>();
                pathcp1.addAll(path);
                combination(candidates,target, resList, curr +1, pathcp1);
            }

        }
    }
}
//leetcode submit region end(Prohibit modification and deletion)

  }